package com.joker.service;

import com.alibaba.fastjson.JSON;
import com.joker.pojo.Content;
import com.joker.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.XPackClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author JokerKS
 * @Date 2022/01/14 11:49
 * @Version 1.0
 */
@Service
public class ContentService {

	@Autowired
	@Qualifier("restHighLevelClient")
	private RestHighLevelClient client;

	@Autowired
	private HtmlParseUtil htmlParseUtil;

	//将解析数据插入es索引中
	public boolean parseContent(String keywords) throws Exception {
		List<Content> contents = htmlParseUtil.parseJD(keywords);

		BulkRequest bulkRequest = new BulkRequest();
		bulkRequest.timeout("2m");

		for (int i = 0; i < contents.size(); i++) {
			bulkRequest.add(new IndexRequest("jd_goods")
					.source(JSON.toJSONString(contents.get(i)), XContentType.JSON)

			);
		}
		BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
		return !bulk.hasFailures();
	}

//	查询操作

	public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
		if (pageNo <= 1) {
			pageNo = 1;
		}

		// 条件搜索
		SearchRequest searchRequest = new SearchRequest("jd_goods");
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

		// 精准匹配
		TermQueryBuilder query = QueryBuilders.termQuery("title", keyword);
		sourceBuilder.query(query);
		sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

		//搜索高亮
		HighlightBuilder highlightBuilder = new HighlightBuilder();
		highlightBuilder.field("title");
		highlightBuilder.requireFieldMatch(false);//关闭多个高亮
		highlightBuilder.preTags("<span style='color:red'>");
		highlightBuilder.postTags("</span>");
		sourceBuilder.highlighter(highlightBuilder);

		sourceBuilder.from(pageNo);
		sourceBuilder.size(pageSize);

		//执行搜索
		searchRequest.source(sourceBuilder);
		SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

		// 解析结果
		List<Map<String, Object>> list = new ArrayList<>();
		for (SearchHit hit : searchResponse.getHits().getHits()) {

			Map<String, HighlightField> highlightFields = hit.getHighlightFields();

			//获取高亮字段
			HighlightField title = highlightFields.get("title");

			//原来的结果
			Map<String, Object> sourceAsMap = hit.getSourceAsMap();

			// 解析高亮的字段，将原来的字段换为我们高亮的字段即可
			if (title != null) {

				Text[] fragments = title.fragments();
				String n_title = "";
				for (Text text : fragments) {
					//将旧的字段保存到新的高亮字段中
					n_title += text;
				}
				//替换原来的title字段
				sourceAsMap.put("title", n_title);
			}
			list.add(sourceAsMap);
		}
		return list;
	}


}
